//
//  ZXVideoEditManager.m
//  cxsj_ios
//
//  Created by ihope on 2018/4/24.
//  Copyright © 2018年 xiaoLin. All rights reserved.
//

#import "ZXVideoEditManager.h"

@implementation ZXVideoEditManager

/**
 @return 地址
 */
+ (NSString *)compressedVideoPath{
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    NSString * resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]];
    return resultPath;
}

/**
 TODO:压缩视频
 */
+ (void)compressedVideoWithPath:(AVURLAsset*)avAsset CompletionHandler:(void (^)(NSURL *path))completionHandler{
//    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:path options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        NSURL *pathUrl = [NSURL fileURLWithPath:[ZXVideoEditManager compressedVideoPath]];
        exportSession.outputURL = pathUrl;
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch (exportSession.status) {
                case AVAssetExportSessionStatusCompleted:
                    completionHandler(pathUrl);
//                    [ZXVideoEditManager deleteFileByPath:pathUrl];
                    break;
                default:
                    break;
            }
        }];
    }
}
-(void)compressionVideoWith:(PHAsset *)asset Complete:(void(^)(NSData *data,NSString *filename,NSURL *fileURL))result{
    
//    PHAsset *asset = (PHAsset *)myAsset;
//    PHAssetResource *resource = [[PHAssetResource assetResourcesForAsset:asset] firstObject];
//    NSString *fileName = resource.originalFilename;
    
    if (asset.mediaType == PHAssetMediaTypeVideo || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHVideoRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
//        long long originFileSize = [[resource valueForKey:@"fileSize"] longLongValue];
////        float fileSize = originFileSize/(1024.0*1024.0);
//        NSLog(@"size is %f",originFileSize/(1024.0*1024.0)); //size is 43.703005
        [[PHImageManager defaultManager]requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            [ZXVideoEditManager compressedVideoWithPath:(AVURLAsset *)avAsset CompletionHandler:^(NSURL *path) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"%@",[path absoluteString]);
                    NSData *data = [NSData dataWithContentsOfURL:path];
                    NSArray *array = [[path absoluteString] componentsSeparatedByString:@"/"];
                    result(data,[array lastObject],path);
                });
                
            }];
        }];
    }
}




/**
 TODO:删除本地文件
 
 @param path 文件地址
 */
+(void)deleteFileByPath:(NSURL *)path{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    BOOL blHave=[fileManager fileExistsAtPath:[path path]];
    if (blHave) {
        [fileManager removeItemAtURL:path error:nil];
    }
}
///获取视频缩略图
+(UIImage *)getScreenShotImageFromVideoPath:(AVURLAsset *)asset{
    UIImage *shotImage;
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 1);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    shotImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return shotImage;
}


@end
